#include <iostream>
#include "codebookmodel.h"
#include "fgfiltering.h"

#define FRAMES_TO_LEARN 25
#define FRAME_HEIGHT 640
#define FRAME_WIDTH 480
int main (int argc, char * const argv[]) {
	FgFiltering *fgFiltering = new FgFiltering(FRAME_HEIGHT, FRAME_WIDTH);
	CodeBookModel *model = new CodeBookModel(FRAME_HEIGHT, FRAME_WIDTH);
	
	//capture from camera
	CvCapture *capture = cvCaptureFromCAM(0);
	if (capture == NULL) {
		cout<<"Error with capture"<<endl;
		exit (-1);
	}
	cvNamedWindow("Raw", CV_WINDOW_AUTOSIZE);
	cvNamedWindow("Foreground", CV_WINDOW_AUTOSIZE);
	cvNamedWindow("FGfiltered", CV_WINDOW_AUTOSIZE);
	IplImage *rawImg = cvQueryFrame(capture);
	IplImage *yuvImg = cvCreateImage(cvGetSize(rawImg), IPL_DEPTH_8U, 3);
	IplImage *fgImg = cvCreateImage(cvGetSize(rawImg), IPL_DEPTH_8U, 1);
	IplImage *fgFiltered = cvCreateImage(cvGetSize(rawImg), IPL_DEPTH_8U, 1);
	IplImage *trueForeground = cvCreateImage(cvGetSize(rawImg), IPL_DEPTH_8U, 3);
	int framesLearned = 0;
	char c;
	bool record = false;
	while (1) {
		rawImg = cvQueryFrame(capture);
		cvFlip(rawImg, NULL, 1);
		cvShowImage("Raw", rawImg);
		c = cvWaitKey(25);
		if (c == 'r')
			record = true;
		if (c == 27)
			break;
		if (!record) //do not record until r key is pressed
			continue;
		cvCvtColor(rawImg, yuvImg, CV_BGR2YCrCb);
		if (framesLearned < FRAMES_TO_LEARN) {
			framesLearned++;
			model->updateBG(yuvImg);
			if (framesLearned == FRAMES_TO_LEARN) {
				model->clearStale();
			}
		//start using the learned data to find the foreground
		}else {
			model->bgDiff(yuvImg, fgImg);
			cvCopy(fgImg, fgFiltered);
			fgFiltering->findConnectedComponents(fgFiltered);
			fgFiltering->segregateTrueForeground(fgFiltered, yuvImg, trueForeground);
			cvShowImage("Foreground", fgImg);
			cvShowImage("FGfiltered", trueForeground);
		}
	}
	 
	cvReleaseImage(&yuvImg);
	cvReleaseImage(&fgImg);
	cvReleaseImage(&fgFiltered);
	cvReleaseImage(&trueForeground);
	cvDestroyWindow("Raw");
	cvDestroyWindow("Foreground");
	cvDestroyWindow("FGfiltered");
	return 0;
}
